
% inputs:
% rootname: a char array that is common to all of the .Raw files you're
% trying to load
% imagesize: [width,height] in pixels
% frames: the frame#'s you're trying to load. If left empty it will load
% all the frames
% binning: post-hoc binning you'd want to do

function mov = loadRawStack_v1(rootname,imagesize,frames,binning,pixels,imtype)
% the input, 'pixels' allows the user to specify which pixels in the image
% to actually load (doesn't save on time, but saves on memory). The index
% of the pixels needs to be linear indexing
if nargin < 5 || isempty(pixels)
    subim = false;
else
    subim = true;
    [N,M] = ind2sub(imagesize,pixels);      %note the assignment here
end
if nargin < 6 || isempty(imtype)
    imtype = 'uint16';
end
fn = dir(['*',rootname,'*','.raw']);
%matlab for some reason doesn't sort these filenames correctly so will have
%to add a separate sorting:
fileorder = zeros(length(fn),1);
expression = '-[1234567890]+.Raw';
altexp = '-[1234567890.]+.Raw';
pat = regexpPattern(expression);
altpat = regexpPattern(altexp);
for n = 1:length(fileorder)
    try
        substr = extract(fn(n).name,pat);
        fileorder(n) = sscanf(substr{1}(2:end),'%d');
    catch
        substr = extract(fn(n).name,altpat);
        fileorder(n) = sscanf(substr{1}(2:end),'%f');
    end
end
[~,I] = sort(fileorder);
fn = fn(I);

if nargin < 3 || isempty(frames)
    frames = 1:length(fn);
end
if nargin < 4 || isempty(binning)
    binning = 1;
end
if ~subim
    mov = zeros(imagesize(1)/binning,imagesize(2)/binning,length(frames));
else
    mov = zeros(range(M)+1,range(N)+1,length(frames));
end
f= waitbar(0,'loading .raw image stack');
for n = 1:length(frames)
    fid = fopen(fn(frames(n)).name,'r');
    temp = fread(fid,imagesize(1)*imagesize(2),imtype);
    if binning > 1
        temp = binimage(temp,binning,imagesize);
    else
        temp = reshape(temp,imagesize(1),imagesize(2));
    end
    if subim
        mov(:,:,n) = reshape(temp(pixels),size(mov,1),size(mov,2));
    else
        mov(:,:,n) = temp;
    end
    fclose(fid);
    waitbar(n/length(frames),f);
end
close(f);
mov = permute(mov,[2,1,3]);


function C = binimage(im,binsize,imagesize)

C = reshape(im,binsize,[]);
C = sum(C);
C = reshape(C,imagesize(1)/ binsize,[]);
C = C';
C = reshape(C,binsize,[]);
C = sum(C);
C = reshape(C,imagesize(2) / binsize,[]);
C = C';
return;
